<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  getProjectList,
  delJmx,
  getJmxInfo,
  getParamsFilesInfo,
  delProject,
  checkJmxFile,
  downloadJmxFile,
  getCreater,
  downloadAllFile
} from "@/api/file";
import { downloadFileWithBuffer } from "@/utils/download";
import { storageSession } from "@pureadmin/utils";
import Delete from "@iconify-icons/ep/delete";
import Download from "@iconify-icons/ep/download";
import {
  ElMessage,
  ElMessageBox,
  ElTable,
  UploadInstance,
  UploadRawFile,
  UploadFile,
  UploadFiles,
  genFileId
} from "element-plus";

defineOptions({
  name: "jmxManagement"
});

type userType = {
  username?: string;
  roles?: Array<string>;
};
type selection = {
  name?: string;
  path?: string;
  lastModified?: string;
  size?: string;
};
const projectList = ref([]);
const projectName = ref("");
const jmxTableData = ref([]);
const csvTableData = ref([]);
const loading = ref(false);
const loading2 = ref(false);
const checkResult = ref("");
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<selection[]>([]);
const upload = ref<UploadInstance>();
const userInfo: userType = storageSession().getItem("user-info");
const createrName = ref("");
const searchScenario = ref("");
const pagination = ref({
  total: 0,
  pageNum: 1,
  pageSize: 10,
})

// 获取项目列表
const getList = async () => {
  try {
    const res = await getProjectList();
    if (res.success) {
      projectList.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};

const getCreaterInfo = async () => {
  try {
    const res = await getCreater({ projectName: projectName.value });
    if (res.success) {
      createrName.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};

const handleChange = (value: string) => {
  searchScenario.value = ''
  storageSession().setItem("jmxProjectName", value);
  if (value) {
    getJmxList();
    getCsvList();
    getCreaterInfo();
  } else {
    jmxTableData.value = [];
  }
};

const getJmxList = async () => {
  try {
    loading.value = true;
    const res = await getJmxInfo({
      projectName: projectName.value,
      name: searchScenario.value,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    });
    loading.value = false;
    if (res.success) {
      jmxTableData.value = res.data.list;
      pagination.value.total = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const getCsvList = async () => {
  try {
    loading2.value = true;
    const res = await getParamsFilesInfo({
      projectName: projectName.value,
    });
    loading2.value = false;
    if (res.success) {
      csvTableData.value = res.data
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading2.value = false;
    ElMessage.error(error);
  }
};

const handleSelectionChange = (val: selection[]) => {
  multipleSelection.value = val;
};

const checkJmx = async () => {
  try {
    loading.value = true;
    const fileNames = multipleSelection.value.map(item => item.name);
    const res = await checkJmxFile({
      projectName: projectName.value,
      fileName: fileNames
    });
    loading.value = false;
    if (res.success) {
      checkResult.value = res.data
      ElMessage.success("检查完成");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const handleDel = async (row: { name: any }) => {
  try {
    loading.value = true;
    const res = await delJmx({
      projectName: projectName.value,
      fileName: row.name
    });
    loading.value = false;
    if (res.success) {
      getJmxList();
      getCsvList();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const handleDownload = async (row: { name: any }) => {
  try {
    loading.value = true;
    const res = await downloadJmxFile({
      projectName: projectName.value,
      fileName: row.name
    });
    loading.value = false;
    downloadFileWithBuffer(res, row.name);
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const handleDownloadAllFile = async () => {
  try {
    let filename = 'testplans'
    loading.value = true;
    const res = await downloadAllFile({ projectName: projectName.value });
    loading.value = false;
    downloadFileWithBuffer(res, filename, res.type);
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const handleSuccess = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("handleSuccess", response, uploadFile, uploadFiles);
  getJmxList();
  getCsvList();
  if (response.success) {
    ElMessage.success(response.msg);
  } else {
    ElMessage.error(response.msg);
  }
};

const handleExceed = (files: UploadRawFile[]) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};

const hanleReomve = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log("hanleReomve", uploadFile, uploadFiles);
};

const handleError = (
  error: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("handleError", error, uploadFile, uploadFiles);
  loading.value = false;
  ElMessage.error(error);
};

const handleBeforeUpload = (rawFile: UploadRawFile) => {
  loading.value = true;
  const fileType = rawFile.name.split(".").pop();
  console.log("handleBeforeUpload", rawFile, fileType);
  if (fileType == "jmx" || fileType == "txt" || fileType == "csv" || fileType == "dat") {
    return true; // 允许文件上传
  }
  ElMessage.error("只允许上传.jmx，.txt，.csv, .dat文件");
  loading.value = false;
  return false; // 返回 false 可以阻止文件上传
};

const handleProjectDel = () => {
  ElMessageBox.confirm(
    "此操作将删除项目下的所有内容（包括脚本、配置等），是否继续?",
    "警告",
    {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      loading.value = true;
      delProject({ projectName: projectName.value })
        .then(res => {
          loading.value = false;
          if (res.success) {
            getList();
            jmxTableData.value = [];
            csvTableData.value = [];
            projectName.value = "";
            ElMessage.success(res.msg);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(error => {
          loading.value = false;
          ElMessage.error(error);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  getJmxList()
}
const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  getJmxList()
}

onMounted(async () => {
  await getList();
  let session: string = storageSession().getItem("jmxProjectName");
  if (projectList.value.includes(session)) {
    projectName.value = session
    getJmxList();
    getCsvList();
    getCreaterInfo();
  }
});
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>脚本管理</span>
      </div>
    </template>
    <div class="action-bar">
      <el-space>
        <el-select filterable v-model="projectName" placeholder="请选择项目" @change="handleChange">
          <el-option v-for="item in projectList" :key="item" :label="item" :value="item" />
        </el-select>
        <el-form-item label="创建人" style="margin-bottom: 0;"><el-input v-model="createrName" clearable disabled />
        </el-form-item>
        <el-input v-model="searchScenario" clearable placeholder="请输入文件名" style="width: 200px;" />
        <el-button type="primary" @click="getJmxList">搜索</el-button>
      </el-space>

      <div style="display: flex">
        <el-button :disabled="multipleSelection.length == 0" @click="checkJmx" style="margin-right: 10px">脚本检查</el-button>
        <el-button v-if="userInfo.roles && userInfo.roles.includes('admin')" style="margin-right: 10px" type="danger"
          :disabled="!projectName" @click="handleProjectDel">删除项目</el-button>
        <el-upload ref="upload" class="upload" action="/api/file/uploadJmx" multiple :show-file-list="false"
          :on-success="handleSuccess" :on-exceed="handleExceed" :on-remove="hanleReomve" :on-error="handleError"
          :before-upload="handleBeforeUpload" accept=".jmx,.txt,.csv" :data="{ projectName: projectName }">
          <el-tooltip class="box-item" effect="dark" content="只允许上传jmx，txt，csv,dat文件" placement="left">
            <el-button type="primary" :disabled="!projectName" style="margin-right: 10px">上传文件</el-button>
          </el-tooltip>
        </el-upload>
        <el-button :disabled="!projectName" type="primary" @click="handleDownloadAllFile">下载全部文件</el-button>

      </div>
    </div>
    <el-table ref="multipleTableRef" v-loading="loading" :data="jmxTableData" stripe border style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="size" label="文件大小" />
      <el-table-column prop="lastModified" label="修改时间" />
      <el-table-column fixed="right" label="操作" width="80">
        <template #default="scope">
          <div class="item-action">
            <el-popconfirm title="你确定要删除此项吗?" width="200" @confirm="handleDel(scope.row)">
              <template #reference>
                <div>
                  <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                    <el-button circle size="small" type="danger">
                      <IconifyIconOffline :icon="Delete" />
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-popconfirm>
            <el-tooltip class="box-item" effect="dark" content="下载" placement="top">
              <el-button circle size="small" type="primary" @click="handleDownload(scope.row)">
                <IconifyIconOffline :icon="Download" />
              </el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-end mt-[10px]">
      <el-pagination background layout="sizes, prev, pager, next, total" :total="pagination.total" :default-page-size="10"
        :current-page="pagination.pageNum" @update:current-page="handleCurrentChange" @size-change="handleSizeChange" />
    </div>
    <el-divider content-position="left">参数化文件</el-divider>
    <el-table ref="multipleTableRef" v-loading="loading2" :data="csvTableData" stripe border style="width: 100%">
      <el-table-column type="index" width="55" />
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="size" label="文件大小" />
      <el-table-column prop="lastModified" label="修改时间" />
      <el-table-column fixed="right" label="操作" width="80">
        <template #default="scope">
          <div class="item-action">
            <el-popconfirm title="你确定要删除此项吗?" width="200" @confirm="handleDel(scope.row)">
              <template #reference>
                <div>
                  <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                    <el-button circle size="small" type="danger">
                      <IconifyIconOffline :icon="Delete" />
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-popconfirm>
            <el-tooltip class="box-item" effect="dark" content="下载" placement="top">
              <el-button circle size="small" type="primary" @click="handleDownload(scope.row)">
                <IconifyIconOffline :icon="Download" />
              </el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template v-if="checkResult">
      <el-divider content-position="left">检查结果</el-divider>
      <el-input v-model="checkResult" readonly :rows="2" type="textarea" autosize />
    </template>
  </el-card>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
